package com.security;

import com.pojo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = tokenService.getTokenFromRequest(request);
        if (!StringUtils.isEmpty(token)) {
            //令牌解析
            UserVo userVo = tokenService.getUserFromToken(token);
            var auth = new TokenAuthentication(userVo, null, null);
            //将认证完成的对象存入SecurityContext
            SecurityContextHolder.getContext().setAuthentication(auth);
            //调用下一个filter
            filterChain.doFilter(request, response);
        } else {
            throw new BadCredentialsException("未授权的访问");
        }
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return request.getServletPath().startsWith("/");
    }
}
